package com.project.controller;

import com.project.base.BaseController;
import com.project.biz.CmsProductBiz;
import com.project.biz.UserBiz;
import com.project.pojo.dto.ProductExportDTO;
import com.project.pojo.dto.UserDTO;
import com.project.pojo.model.ProductModel;
import com.project.pojo.model.UserQuery;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Description: 导出
 * @Author: zhuchi
 * @CreateDate: 2020/8/20 23:54
 * @Version: 1.0
 */
@Slf4j
@Api(value = "ExportController", description = "导出")
@RestController
@RequestMapping(value = "/export")
public class ExportController extends BaseController {

    /**
     * 商品业务层接口类
     */
    @Autowired
    private CmsProductBiz productBiz;

    /**
     * 用户业务层接口类
     */
    @Autowired
    private UserBiz userBiz;

    /**
     * 导出商品
     * @param response
     */
    @PostMapping(value = "/exportProductData")
    public void exportProductData(ProductModel productModel, HttpServletResponse response){
        //按条件查询商品
        List<ProductExportDTO> result = this.productBiz.selectExportProductData(productModel);

        try {
            ClassPathResource resource = new ClassPathResource("static/product.xlsx");
            //创建工作薄对象
            XSSFWorkbook workbook = new XSSFWorkbook(resource.getInputStream());
            if (null != result && result.size() > 0){
                //获取第一个sheet
                XSSFSheet sheet = workbook.getSheetAt(0);

                //行索引
                int rowIndex = 1;

                XSSFRow row = null;
                for (ProductExportDTO productExportDTO : result){
                    //创建行
                    row = sheet.createRow(rowIndex);
                    row.createCell(0).setCellValue(productExportDTO.getProductId()+"");
                    row.createCell(1).setCellValue(StringUtils.isNotBlank(productExportDTO.getBrand()) ? productExportDTO.getBrand() : "");
                    row.createCell(2).setCellValue(StringUtils.isNotBlank(productExportDTO.getName()) ? productExportDTO.getName() : "");
                    row.createCell(3).setCellValue(StringUtils.isNotBlank(productExportDTO.getSpecData()) ? productExportDTO.getSpecData() : "");
                    row.createCell(4).setCellValue(StringUtils.isNotBlank(productExportDTO.getProductCode()) ? productExportDTO.getProductCode() : "");
                    row.createCell(5).setCellValue(StringUtils.isNotBlank(productExportDTO.getSupplier()) ? productExportDTO.getSupplier() : "");
                    row.createCell(6).setCellValue(StringUtils.isNotBlank(productExportDTO.getCategoryNameOne()) ? productExportDTO.getCategoryNameOne() : "");
                    row.createCell(7).setCellValue(StringUtils.isNotBlank(productExportDTO.getCategoryNameTwo()) ? productExportDTO.getCategoryNameTwo() : "");
                    row.createCell(8).setCellValue(null != productExportDTO.getPrice() ? productExportDTO.getPrice()+"" : "");
                    row.createCell(9).setCellValue(null != productExportDTO.getOriginalPrice() ? productExportDTO.getOriginalPrice()+"" : "");
                    row.createCell(10).setCellValue(null != productExportDTO.getFavorablePrice() ? productExportDTO.getFavorablePrice()+"" : "");
                    row.createCell(11).setCellValue(null != productExportDTO.getStock() ? productExportDTO.getStock()+"" : "");
                    row.createCell(12).setCellValue(null != productExportDTO.getSales() ? productExportDTO.getSales()+"" : "");
                    rowIndex++;
                }
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Type","application/vnd.ms-excel");
            response.setHeader( "Content-Disposition", "attachment;filename=" + new String( "product.xlsx".getBytes("GB2312"), "8859_1" ));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出用户
     * @param response
     */
    @PostMapping(value = "/exportUserData")
    public void exportUserData(UserQuery userQuery, HttpServletResponse response){
        //按条件查询用户
        List<UserDTO> result = this.userBiz.getUser(userQuery);

        try {
            ClassPathResource resource = new ClassPathResource("static/users.xlsx");
            //创建工作薄对象
            XSSFWorkbook workbook = new XSSFWorkbook(resource.getInputStream());
            if (null != result && result.size() > 0){
                //获取第一个sheet
                XSSFSheet sheet = workbook.getSheetAt(0);

                //行索引
                int rowIndex = 1;

                XSSFRow row = null;
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                BigDecimal zero = new BigDecimal("0.00");
                for (UserDTO userDTO : result){
                    //创建行
                    row = sheet.createRow(rowIndex);
                    row.createCell(0).setCellValue(userDTO.getBaseUserId()+"");
                    row.createCell(1).setCellValue(StringUtils.isNotBlank(userDTO.getWxNickname()) ? userDTO.getWxNickname() : "");
                    row.createCell(2).setCellValue(StringUtils.isNotBlank(userDTO.getMobile()) ? userDTO.getMobile() : "");
                    row.createCell(3).setCellValue(format.format(userDTO.getCreateTime()));
                    row.createCell(4).setCellValue(userDTO.getUserType() == 1 ? "是" : "否");
                    row.createCell(5).setCellValue(userDTO.getBalance()+"");
                    //充值总获得金额：充值金额 + 赠送金额
                    BigDecimal totalRechargeAndDonation = zero;
                    if (userDTO.getTotalRechargeAmount().compareTo(zero) == 1){
                        totalRechargeAndDonation = userDTO.getTotalRechargeAmount().add(userDTO.getTotalDonationAmount());
                    }
                    row.createCell(6).setCellValue(null != userDTO.getTotalRechargeAmount() ? userDTO.getTotalRechargeAmount()+"" : "");
                    row.createCell(7).setCellValue(null != userDTO.getTotalDonationAmount() ? userDTO.getTotalRechargeAmount()+"" : "");
                    row.createCell(8).setCellValue(totalRechargeAndDonation + "");
                    //商品订单均价：商品订单总金额 / 商品订单总数
                    BigDecimal productOrderAvg = zero;
                    if (userDTO.getProductTotalAmount().compareTo(zero) == 1){
                        productOrderAvg = userDTO.getProductTotalAmount().divide(new BigDecimal(userDTO.getOrderNum()), 2, RoundingMode.HALF_UP);
                    }
                    row.createCell(9).setCellValue(null != userDTO.getOrderNum() ? userDTO.getOrderNum()+"" : "");
                    row.createCell(10).setCellValue(null != userDTO.getProductTotalAmount() ? userDTO.getProductTotalAmount()+"" : "");
                    row.createCell(11).setCellValue(productOrderAvg+"");
                    //回收订单均价：回收订单总金额 / 回收订单总数
                    BigDecimal recoveryOrderAvg = zero;
                    if (userDTO.getRecoveryTotalAmount().compareTo(zero) == 1){
                        recoveryOrderAvg = userDTO.getRecoveryTotalAmount().divide(new BigDecimal(userDTO.getRecoveryOrderNum()), 2, RoundingMode.HALF_UP);
                    }
                    row.createCell(12).setCellValue(null != userDTO.getRecoveryOrderNum() ? userDTO.getRecoveryOrderNum()+"" : "");
                    row.createCell(13).setCellValue(null != userDTO.getRecoveryTotalAmount() ? userDTO.getRecoveryTotalAmount()+"" : "");
                    row.createCell(14).setCellValue(recoveryOrderAvg+"");
                    rowIndex++;
                }
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Type","application/vnd.ms-excel");
            response.setHeader( "Content-Disposition", "attachment;filename=" + new String( "users.xlsx".getBytes("GB2312"), "8859_1" ));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
